// ignore_for_file: unused_local_variable

/*
 * @Author: CodeHare
 * @Date: 2023-10-31 16:58:16
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-03-04 19:01:12
 * @Description: EMS参数设置
 */
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/self_develop_ems_romote_control/ems_params_setting/widgets/battery_set_widget.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/self_develop_ems_romote_control/ems_params_setting/widgets/converter_set_widget.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/self_develop_ems_romote_control/ems_params_setting/widgets/energy_management_widget.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/self_develop_ems_romote_control/ems_params_setting/widgets/system_set_widget.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/user_entity_manager.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';

import '../../../../../../../components/log_utils.dart';

class EmsParamsSettingController extends GetxController
    with GetTickerProviderStateMixin {
  late TabController tabController;
  late RefreshController currentRefreshController;

  /// 在线状态
  late ConnectStatusType connectStatus;
  late String deviceId;
  DeviceServices deviceServices = Get.find<DeviceServices>();
  bool commandExecutionSuccessful = false;

  /// 角色
  int? role;

  ///  标题
  String title = '${ResKey.deviceParameterSetting.tr}';
  List<String> tabs = [];
  List<Widget> tabsViews = [];

  @override
  void onInit() {
    super.onInit();
    _inheritArguments();
    _readInheritParams();
    _readCacheRole();
    _generateTabTitle();
    _generateTabView();
    Log.d("=== EMS参数设置模块 ===$connectStatus");
    tabController = TabController(length: tabs.length, vsync: this);
  }

  /// 继承来自父级的数据
  void _inheritArguments() {
    if (Get.arguments != null) {
      deviceId = Get.arguments['deviceId'].toString();
      connectStatus = Get.arguments['connectStatus'];
    }
  }

  /// 读取继承参数
  void _readInheritParams() {
    if (Get.arguments != null) {
      deviceId = Get.arguments['deviceId'].toString();
    }
  }

  /// 读取缓存角色
  void _readCacheRole() {
    var roles = UserEntityManager().load().roles;
    role = roles![0].roleId!;
  }

  /// 获取展示TabTitle
  void _generateTabTitle() {
    tabs.clear();

    // if (role == RoleType.owner.value || role == RoleType.installer.value) {
    tabs.addAll([
      ResKey.deviceSystemSetting.tr, // '系统设置',
      ResKey.deviceEnergyManagement.tr, //  '能量管理',
    ]);
    // return;
    // }

    // tabs.addAll([
    //   '系统设置',
    //   '变流器设置',
    //   '电池设置',
    //   '能量管理',
    // ]);
  }

  /// 获取展示TabView
  void _generateTabView() {
    tabsViews.clear();

    // if (role == RoleType.owner.value || role == RoleType.installer.value) {
    tabsViews.addAll([
      SystemSettingWidget(deviceId, role!),
      EnergyManagementWidget(
        deviceId,
      ),
    ]);
    //   return;
    // }

    // tabsViews.addAll([
    //   SystemSettingWidget(deviceId, role!),
    //   ConverterSetWidget(deviceId),
    //   BatterySetWidget(deviceId),
    //   EnergyManagementWidget(
    //     deviceId,
    //   ),
    // ]);
  }

  /// 下发指令接口
  Future sendCommand(context, params) => Configs.httpClient.requestWithLoading(
        () async {
          var res = await deviceServices.deviceRemoteSetting(params);
          // print("执行执行成功啦 $res");
          commandExecutionSuccessful = true;
          FuncUtils.requestTipsDislog(context, ResKey.executeSuccess.tr, true);

          Future.delayed(
            const Duration(
              milliseconds: 1000,
            ),
            () => Get.back(),
          );
          update();
        },
        onError: (err) {
          commandExecutionSuccessful = false;
          // print("执行执行失败啦 $commandExecutionSuccessful");
          FuncUtils.requestTipsDislog(context, ResKey.executeFailure.tr, false);

          Future.delayed(
            const Duration(
              milliseconds: 1000,
            ),
            () => Get.back(),
          );
          return true;
        },
      );
}
